/**
 * There are <a href="https://github.com/ketayao/keta-custom">keta-custom</a> code generation
 */
package fms.controller;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import fms.core.DateUtil;
import fms.core.SysConstants;
import fms.service.CptSendService;
import com.ketayao.ketacustom.entity.main.User;
import com.ketayao.ketacustom.service.UserService;
import com.ketayao.ketacustom.shiro.ShiroUser;
import com.ketayao.ketacustom.util.dwz.Page;

@Controller
@RequestMapping("/management/chartController")
public class ChartController {

	@Autowired
	private CptSendService cptSendService;

	@Autowired
	private UserService userService;
	
	@InitBinder
	public void dataBinder(WebDataBinder dataBinder) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(df,
				true));
	}
 
	// 本日飞行计划发送信息统计
	@RequestMapping(value = "/flpChart", method = { RequestMethod.GET,RequestMethod.POST },produces = "text/html;charset=GBK"  )
	@ResponseBody
	public String flightPlanSendInfoStatistics(ServletRequest request, Page page, Map<String, Object> map) { 
//System.out.println("flightPlanSendInfoStatistics");
		// 用于拼接Funshion所需要的xml数据
		StringBuffer buffer = new StringBuffer();
//		每个拼接的value都是一个百分比（即，比例是自己算出来的）
//		buffer.append("<graph unescapeLinks='0' decimalPrecision='2' numberSuffix='%25' caption='飞行计划上传统计图'> ");
//		每个拼接的value仅是一个数量（即，比例图形插件自己算的）
		//  caption='飞行计划上传统计图'
		buffer.append("<graph showPercentageValues='1'> ");
		try {
			Subject subject =org.apache.shiro.SecurityUtils.getSubject();		
			ShiroUser shiroUser = (ShiroUser)subject.getPrincipal();		
			User user = userService.getByUsername(subject.getPrincipal().toString());	
			
			// 获取当天的UTC起始、终止时间
			String startDate = DateUtil.getCurUTCtime(SysConstants.FORMAT_DATE); 	
			String endDate = DateUtil.changeHour(DateUtil.getCurUTCtime(SysConstants.FORMAT_DATE), 24,SysConstants.FORMAT_DATE );

			// 获取飞行计划总数
			List totalList = cptSendService.getAllFlightPlanCount(startDate, endDate, user.getOrganization().getAirlines());
			BigDecimal totalall = (BigDecimal)totalList.get(0);
			
			List countByDifStatuslist = cptSendService.getFlyPlanSumByStatusGroup(startDate, endDate, user.getOrganization().getAirlines());				
			
			if (1 == totalall.compareTo(new BigDecimal(0))) {
				for(int i = 0; i < countByDifStatuslist.size(); i++) {
					Object object[] = (Object[])countByDifStatuslist.get(i);
					BigDecimal statuscount = (BigDecimal)object[0];
					if ("2".equals(object[1])){
						buffer.append(" <set label='未发送' value='" + statuscount + "'></set>");  
					} else {
						// 理论上：这里统计的“已发送”包含了数据库字段发送状态的中“已发送、REJ、AK”三种状态
						buffer.append(" <set label='已发送' value='" + statuscount + "'></set>"); 
					}
				}
			} else {
				buffer.append(" <set label='今日暂无飞行计划' value='1'></set>"); 
			}
			buffer.append(" </graph>");
		} catch (ParseException e) {
			e.printStackTrace();
		}  
		return buffer.toString();
	}
	
	// 本日风温上传信息统计
	@RequestMapping(value = "/widChart", method = { RequestMethod.GET,RequestMethod.POST },produces = "text/html;charset=GBK")
	@ResponseBody
	public String windSendInfoStatistics(ServletRequest request, Page page, Map<String, Object> map) { 
//System.out.println("windSendInfoStatistics");
		StringBuffer buffer = new StringBuffer();
		//  caption='风温数据上传统计图'
		buffer.append("<graph showPercentageValues='1'> ");
		try {
			Subject subject =org.apache.shiro.SecurityUtils.getSubject();		
			ShiroUser shiroUser = (ShiroUser)subject.getPrincipal();		
			User user = userService.getByUsername(subject.getPrincipal().toString());	

//System.out.println("Airlines:" + user.getOrganization().getAirlines());
			
			
			// 获取当天的UTC起始、终止时间
			String startDate = DateUtil.getCurUTCtime(SysConstants.FORMAT_DATE); 	
			String endDate = DateUtil.changeHour(DateUtil.getCurUTCtime(SysConstants.FORMAT_DATE), 24, SysConstants.FORMAT_DATE);
			
			// 获取风温回复报文总数
			List countList = cptSendService.getAllWindReplyCount(startDate, endDate, user.getOrganization().getAirlines());
			BigDecimal totalall = (BigDecimal)countList.get(0);
			
//			buffer.append("<graph decimalPrecision='2' numberSuffix='%25' caption='风温数据上传统计图' unescapeLinks='0'> ");
			
			// 获取不同发送状态的风温报文数量及其状态
			List list = cptSendService.getWindReplySumByStatusGroup(startDate, endDate, user.getOrganization().getAirlines());
			
			if(1 == totalall.compareTo(new BigDecimal(0))){
				for(int i = 0; i < list.size(); i++){
					Object object[] = (Object[])list.get(i);
					BigDecimal statuscount = (BigDecimal)object[0];
					if ("1".equals(object[1])){				 
						buffer.append(" <set label='已发送' value='" + statuscount + "'></set>");  
					} else if ("3".equals(object[1])){
						buffer.append(" <set label='没有飞行计划' value='" + statuscount + "'></set>");  
					} else if ("4".equals(object[1])){
						buffer.append(" <set label='数据缺失' value='" + statuscount + "'></set>");   
					} else if ("REJ".equals(object[1])){
						buffer.append(" <set label='FMC拒绝' value='" + statuscount + "'></set>");  
					} else if ("AK".equals(object[1])){
						buffer.append(" <set label='FMC确认 ' value='" + statuscount + "'></set>");  
// 风温核心处理模块，暂未考虑“activemq异常...”导致报文“未发送”的情况
//					} else if ("2".equals(object[1])){
//						buffer.append(" <set label='未发送' value='" + statuscount + "'></set>");  
					} 
				}
			} else {
				buffer.append(" <set label='今日暂无风温报文上传' value='1'></set>"); 
			}
			
			buffer.append(" </graph>");
		} catch (ParseException e) {
			e.printStackTrace();
		}  
		return buffer.toString();
	}

}
